from django.http import HttpResponse
from urllib import urlopen
import json
import util

def search(request):
    host = request.get_host()

    # Get the google books reference for the search request
    args = dict(request.GET.items())
    opts = {'indent': None, 'max': 0, 'offset': 0}
    for o in ['indent', 'max', 'offset']:
        if o in args:
            opts[o] = int(args[o])
            del args[o]

    # Handle alternate arguments
    if 'image' in args:
        return HttpResponse('http://www.google.com/intl/en_us/images/logos/product_search_logo_lg.gif', mimetype='text/plain')
    if 'limit' in args:
        return HttpResponse('20', mimetype='text/plain')

    if 'isbn' in args: 
        isbn = util.isbn_10_13(args['isbn']) if len(args['isbn']) == 10 else args['isbn']
        if len(isbn) != 13: raise Exception('Invalid isbn \'%s\'' % isbn)
        req = 'isbn=%s' % isbn
    else:
        req = 'q=%s' % ' '.join([args[arg] for arg in args if arg != 'isbn'])

    fp = urlopen('http://%s/api/books?%s' % (host, req))
    try:
        data = json.load(fp)
    except: return util.error(0)
    finally: fp.close()
    if str(data) == '0': return util.error(0) 

    # For each item in the response, search the products api for the 
    # equivalent isbn
    items = []
    for item in data:
        item = item['attributes']
        if 'isbn_13' not in item: continue
        fp = urlopen('http://%s/api/products?gtin=%s' % (host, item['isbn_13']))
        try: 
            prod = json.load(fp)
        except: return util.error(0)
        finally: fp.close()

        # Find the lowest priced item in the product set for each condition
        new, used = None, None
        if str(prod) == '0': continue
        for p in prod:
            p = p['attributes']
            if 'price_new' in p:
                if new is None: new = p
                else:
                    if float(p['price_new']) < float(new['price_new']): new = p
            elif 'price_used' in p:
                if used is None: used = p
                else:
                    if float(p['price_used']) < float(used['price_used']): used = p

        if new is not None:
            nitm = dict(item)
            nitm['price_new'] = new['price_new']
            nitm['purchase_url'] = new['purchase_url']
            if 'image_url' in new: nitm['image_url'] = new['image_url']
            items.append({'type': 'book', 'attributes': nitm})
        if used is not None:
            uitm = dict(item)
            uitm['price_used'] = used['price_used']
            uitm['purchase_url'] = used['purchase_url']
            if 'image_url' in used: uitm['image_url'] = used['image_url']
            items.append({'type': 'book', 'attributes': uitm})

    if opts['max'] == 0: opts['max'] = len(items)
    return HttpResponse(json.dumps(items[opts['offset']:(opts['max']+opts['offset'])], 
    indent = opts['indent']), mimetype = 'application/json')
